var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const session = require('express-session');
const flash = require('connect-flash');
const log = require("./sql/Log");
const uuid = require("uuid");

var loginRouter = require('./routes/login');
var indexRouter = require('./routes/index');
var orderRouter = require('./routes/order');
var userRouter = require('./routes/user');
var dashboardRouter = require('./routes/dashboard');
var settingRouter = require('./routes/setting');
var commissionRouter = require('./routes/commission');
var setPasswordRouter = require('./routes/setPassword');
var customerRouter = require('./routes/customer');
var api = require('./api/index');

const multer  = require('multer')

var app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
  secret: '富扬游轮',
  resave: false,
  saveUninitialized: true,
  cookie: { maxAge: 1000 * 60 * 60 * 24 }
}))
app.use(flash());
app.use((req, res, next) => {
  res.locals.messages = req.flash();
  next();
});

app.use(multer({dest: './uploads'}).any())

app.use('/api', api);
app.use('/login', loginRouter);
app.use('/dashboard', dashboardRouter);

// 登录验证
app.all("*", (req,res,next)=>{
  if(req.session.userData && req.session.userData.isLogin===1){
    next();
  }else{
    res.redirect('/login');
  }
})

// 权限验证
app.all("*", (req, res, next)=>{
  if(!req.path.includes(".")){
    const userData = req.session.userData;
    const { power, employeesName } = userData;
    let path = req.path;
    if(path === "/user/power/set") path = '/user/power';
    if(path === "/order/add/handle") path = '/order/add';
    if(power.includes( path )){
      next();
    }else{
      res.render("nopower", {
        employeesName,
        index: 0
      });
    }
  }else{
    next();
  }
} )

// 日志记录
app.all("*", (req, res, next)=>{
  const userData = req.session.userData;
  const {employeesName} = userData;
  if(!req.path.includes(".") && req.path.match(/\//g).length>1 && !req.path.includes('/dashboard/getData')){
    log.insertMany({
      lId: "log-"+uuid.v1(),
      message: employeesName + " 访问了 " + req.path + ", 携带的数据为" + JSON.stringify( req.method==="GET" ? req.query : req.body),
      time: Date.now()
    })
  }
  next();
})

app.use('/', indexRouter);
app.use('/index', indexRouter);
app.use('/order', orderRouter);
app.use('/user', userRouter);
app.use('/setting', settingRouter);
app.use('/commission', commissionRouter);
app.use('/setpassword', setPasswordRouter);
app.use('/customer', customerRouter);

app.use(function(req, res, next) {
  next(createError(404));
});

app.use(function(err, req, res, next) {
  console.log(err)
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
